<!--
* description: 财务管理-备件网点价格折让设置
* author: wangjuan
* createdDate: 2021-3-4
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/pa/financialManagement'

export default {
  name: 'SparePartsPriceDiscountSetting',

  components: {
    OneTableTemplate
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      selectData: [],
      rowData: {},
      // 网格查询API配置对象
      apiConfig: api.queryPartPriceDiscountDlr,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save'),
          position: 'right'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey5',
          size: 'small',
          name: 'export',
          clickEvent: () => this.exportExcel(),
          text: this.$t('sys.button.export'),
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'importTemplate',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          position: 'upload'
        },
        {
          compKey: 'btnKey5',
          type: 'text',
          size: 'small',
          name: 'importTemplateDownload',
          icon: 'iconfont  icon-importTemplateDownload',
          click: () => this.templateDownload(),
          text: 'Excel导入模板下载',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点类型：',
              codeField: 'dlrType',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'dlrType,dlrTypeCn',
              customObj: {
                api: api.queryDlrTypes,
                listQuery: {
                  dlrType: ''
                },
                selectType: '1'
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/pa/dlrCode'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/pa/partSelect'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              disabled: true,
              component: () => import('@/components/org/commonSelect'),
              oFields: 'partRepairType,partRepairTypeCn',
              customObj: {
                api: api.queryRepairTypes,
                listQuery: {
                  partRepairType: ''
                },
                selectType: '1'
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '状态：',
              codeField: 'isEnable',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'isEnable,isEnableCn',
              options: [
                { isEnable: '1', isEnableCn: '启用' },
                { isEnable: '0', isEnableCn: '禁用' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey8',
              labelName: '有效时间：',
              codeField: 'effectiveDateBegin,effectiveDateEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'dlrId',
              label: '网点ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'pointPriceDiscountId',
              label: '网点价格折让ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrTypeCn',
              label: '网点类型'
            },
            {
              prop: 'dlrCode',
              label: '网点编码'
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            },
            {
              prop: 'partRepairTypeCn',
              label: '维修类型'
            },
            {
              prop: 'pointPriceDiscount',
              label: '折扣'
            },
            {
              prop: 'effectiveDateBegin',
              label: '有效时间(始)'
            },
            {
              prop: 'effectiveDateEnd',
              label: '有效时间(止)'
            },
            {
              prop: 'isEnableCn',
              label: '状态'
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        dlrType: '',
        dlrCode: '',
        dlrShortName: '',
        partNo: '',
        partName: '',
        partRepairType: '',
        isEnable: '',
        effectiveDateBegin: '',
        effectiveDateEnd: '',
        remark: '',
        dlrId: '',
        pointPriceDiscountId: '',
        partId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        },

        onRowDbClick: this.rowClickModel
      }

    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    rowClickModel(row) {
      this.rowData = row
      this.formField.dlrType = row.dlrType
      this.formField.dlrCode = row.dlrCode
      this.formField.dlrShortName = row.dlrShortName
      this.formField.partNo = row.partNo
      this.formField.partName = row.partName
      this.formField.partRepairType = row.partRepairType
      this.formField.isEnable = row.isEnable
      this.formField['effectiveDateBegin,effectiveDateEnd'] = [row.effectiveDateBegin, row.effectiveDateEnd]
      this.formField.pointPriceDiscountId = row.pointPriceDiscountId
      this.formField.remark = row.remark
      this.formField.dlrId = row.dlrId
      this.formField.partId = row.partId
      this.formField.updateControlId = row.updateControlId
    },

    // 保存
    save() {
      const that = this
      const queryObj = {
        apiConfig: api.savePartPriceDiscountDlr,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.reset()
          this.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
          this.reset()
          this.queryTable(1)
        }
      })
    },

    // 导入
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = api.uploadPartPriceDiscountDlr.APIUrl
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTable()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(_ => {})
    },

    // 模板下载
    templateDownload() {
      this.$requestAPI({
        variables: { dataType: 'excel' },
        apiUrl: api.downPartPriceDisTemplate.APIUrl
      }).then(res => {
        this.$utils.downloadFile(res, '备件网点价格折让设置导入模板下载.xlsx')
      })
    },

    // 导出
    exportExcel() {
      const fileName = this.$utils.fileNameWithTime('备件网点价格折让设置.xlsx')
      this.$requestAPI({
        apiUrl: api.exportPartPriceDiscountDlr.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
